package com.ziq.zcamp.dialog.share

import android.content.Context
import android.graphics.Bitmap
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.Toast
import com.gmlive.camp.dialog.share.SharePicCacheInterface
import com.ziq.zcamp.R
import com.ziq.zcamp.api.request.common.MiniACodeParam
import com.ziq.zcamp.api.service.ApiUrlHelper
import com.ziq.zcamp.bean.post.PostingDetail
import com.ziq.zcamp.constant.H5Url
import com.ziq.zcamp.databinding.LayoutSharePicCachePostBinding
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.UserManager
import com.ziq.zcamp.util.ImageUtil
import com.ziq.zcamp.util.StorageUtil
import com.ziq.zcamp.util.io.IOUtils
import java.io.FileOutputStream

class SharePicCacheLayoutPost @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr), SharePicCacheInterface {

    var binding : LayoutSharePicCachePostBinding = LayoutSharePicCachePostBinding.inflate(LayoutInflater.from(context), this, true)

    var imageList = mutableListOf<String>()
    var way = ""

    var postingDetail : PostingDetail? = null

    private val uidSuffix by lazy{
        val id = UserManager.instance.userInfo.value?.id.toString()
        if (id.isEmpty()){
            ""
        }else{
            "&shareuid=${id}"
        }
    }

    fun setPostingData(data: PostingDetail){
        postingDetail = data
        way = "posting"
        binding.containerPosting.visibility = View.VISIBLE
        data.user?.let {
            binding.name.text = it.nick_name
            val avatorUrl = it.header_url?:""
            binding.avator.setImageURI(avatorUrl)
            if(avatorUrl.isNotEmpty()){
                imageList.add(avatorUrl)
            }
        }

        data.post?.let {
            val imageUrl = it.images?.get(0)?.url?:""
            if(imageUrl.isNotEmpty()){
                imageList.add(imageUrl)
            }
            binding.imagePosting.setImageURI(imageUrl)

            if(it.title?.isNotEmpty() == true){
                binding.title.visibility = View.VISIBLE
                binding.title.text = it.title
            }
            if(it.content?.isNotEmpty() == true){
                binding.content.visibility = View.VISIBLE
                binding.content.text = it.content
            }
            if(it.p_type == 2){
                binding.ivVideoBtn.visibility = View.VISIBLE
                binding.tvPostTypeDescription.text = "发布了一个视频"
            } else if(it.p_type == 3){
                binding.tvPostTypeDescription.text = "发布了一篇文章"
            }


            getSanCode(finish = { minCodeUrl, bitmap ->
                if(minCodeUrl.isNotEmpty()){
                    imageList.add(minCodeUrl)
                }
                isScanCodeSuccess = true
            })
        }

    }

    var isScanCodeSuccess = false
    fun getSanCode(finish: ((minCodeUrl:String, bitmap: Bitmap?) -> Unit)? = null){

        var url = ""
        var miniPagePath = ""
        var miniPageScene = ""
        when(postingDetail?.post?.p_type){
            1, 3->{
                url = "${H5Url.POSTING_DETAIL.url}?id=${postingDetail?.post?.post_id}&creatorId=${postingDetail?.user?.uid}${uidSuffix}"
                miniPagePath = "subpages/community/post-detail/index"
                miniPageScene = "id=${postingDetail!!.post?.post_id}&creatorId=${postingDetail!!.user?.uid}${uidSuffix}&share_cv="
            }
            2->{
                url = "${H5Url.POST_VIDEO_DETAIL.url}?id=${postingDetail?.post?.post_id}&creatorId=${postingDetail?.user?.uid}${uidSuffix}"
                miniPagePath = "subpages/community/video-detail/index"
                miniPageScene = "id=${postingDetail!!.post?.post_id}&creatorId=${postingDetail!!.user?.uid}${uidSuffix}&share_cv="
            }
            else -> {
            }
        }

        ShareUtil.getSanCode(MiniACodeParam().apply {
            is_hyaline = true
            page = miniPagePath
            scene = miniPageScene
            width = 280.toString()
        }, url,  onSuccess = { minCodeUrl:String, bitmap: Bitmap->
            binding.qrCode.post {
                binding.qrCode.setImageBitmap(bitmap)
            }
            finish?.invoke(minCodeUrl, bitmap)
            if(minCodeUrl.isNotEmpty()){
                binding.qrCodeBottomTxt.text = "识别小程序码 阅读完整内容"
            } else {
                binding.qrCodeBottomTxt.text = "识别二维码 阅读完整内容"
            }
        }, onFail = {
            finish?.invoke("", null)
        })
    }

    /**
     * 图片加载完成
     */
    override fun checkPictureBitmap(action : ()->Unit){
        val length = imageList.size
        var index = -1
        fun callback(){
            index++
            if(index < length){
                val url = imageList[index]
                ImageUtil.getBitmap(0, url, 0, 0) { _, _ ->
                    callback()
                }
            } else {
                action.invoke()
            }
        }
        if(isScanCodeSuccess){
            callback()
        } else {
            getSanCode(finish = { minCodeUrl, bitmap->
                callback()
            })
        }
    }


    override fun getMiniProgramPath(): String {
        if(postingDetail != null ){
            return when(postingDetail?.post?.p_type){
                1,3->{
                    "/subpages/community/post-detail/index?id=${postingDetail!!.post?.post_id}&creatorId=${postingDetail!!.user?.uid}${uidSuffix}"
                }
                2->{
                    "/subpages/community/video-detail/index?id=${postingDetail!!.post?.post_id}&creatorId=${postingDetail!!.user?.uid}${uidSuffix}"
                }
                else -> {
                    ""
                }
            }
        }
        return "/pages/community/index"
    }

    /**
     * 完整卡片
     */
    override fun getTotalLayoutBitmap() : Bitmap?{
        return ImageUtil.convertViewToBitmap(binding.root,
            GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_375),
            GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_667))
    }

    /**
     * 小程序分享标题
     */
    override fun getTitleForMiniProgram() : String{
        if(postingDetail != null ){
            var content = ""
            if(postingDetail?.post?.title?.isNotEmpty() == true){
                content = "${postingDetail?.post?.title}"
            }else if(postingDetail?.post?.content?.isNotEmpty() == true){
                content = "${postingDetail?.post?.content}"
            }
            return content
        }
        return ""
    }
    /**
     * 小程序分享卡片封面
     */
    override fun getCoverBitmapForMiniProgram(action : (bitmap : Bitmap?)->Unit){
        var pic = ""
        if(postingDetail != null ){
            if(postingDetail?.post?.images?.get(0)?.url?.isNotEmpty() == true){
                pic = postingDetail?.post?.images?.get(0)?.url?:""
            }
        }
        ImageUtil.getBitmap(0, pic, 0, 0) { _, bitmap ->
            action.invoke(bitmap)
        }
    }
    /**
     * 复制链接
     */
    override fun getLinkTxt() : String{
        if(postingDetail != null ){
            val url = when(postingDetail?.post?.p_type){
                1,3->{
                    "${H5Url.POSTING_DETAIL.url}?id=${postingDetail?.post?.post_id}&creatorId=${postingDetail?.user?.uid}"
                }
                2->{
                    ApiUrlHelper.instance.getUrl("${H5Url.POST_VIDEO_DETAIL.url}?id=${postingDetail?.post?.post_id}&creatorId=${postingDetail?.user?.uid}")
                }
                else -> {
                    ""
                }
            }

            var name = "TA"
            if(UserManager.instance.isLogin.value == true){
                name = UserManager.instance.userInfo.value?.nick_name?:"TA"
            }
            return "[${name}]正在「觅野CAMP」分享自己的生活，来看看吧~\n $url"
        }
        return ""
    }

    /**
     * 保存到本地
     */
    override fun onSavePicToLocal(source:String,finish:()->Unit){
        checkPictureBitmap {
            savePicToLocal(source,getTotalLayoutBitmap())
            finish()
        }
    }

    private fun savePicToLocal(source:String,bitmap : Bitmap?){
        try {
            if(bitmap != null){
                val path = StorageUtil.getPictureFileWith("camp_share_${way}_${System.currentTimeMillis()}.png")
                var fos: FileOutputStream? = null
                try {
                    fos = FileOutputStream(path)
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
                    fos.flush()
                } catch (e: Exception) {
                } finally {
                    IOUtils.close(fos)
                }
                if (path.exists() && path.length() > 0) {
                    ImageUtil.insertImageToAlbum(context, path.absolutePath)
                    val msg = GlobalContextManager.getString(R.string.share_save_success_toast)
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                } else {
                    val msg = GlobalContextManager.getString(R.string.share_save_fail_toast)
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                }
            }
        } catch (ignore: Exception) {
            val msg = GlobalContextManager.getString(R.string.share_save_fail_toast)
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
        }
    }
}